package edu.njfu.mystudentapp

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import edu.njfu.mystudentapp.adapter.InfoAdapterByRecyclerView
import edu.njfu.mystudentapp.model.Info
import edu.njfu.mystudentapp.model.Student
import edu.njfu.mystudentapp.service.StudentService
import edu.njfu.mystudentapp.utils.ServerCreator
import kotlinx.android.synthetic.main.activity_student_information.*
import okhttp3.ResponseBody
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Func1
import rx.schedulers.Schedulers

class StudentInformationActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_student_information)
        var info=intent.getStringExtra("studentInformation")
        var student= Gson().fromJson(info,Student::class.java)
        if(student.gender=="女"){
            loadImage(1)
        }else{
            loadImage(0)
        }
        var list=initInfo(student)
        var layoutManager= LinearLayoutManager(this)
        infoRecyclerView.layoutManager=layoutManager
        var adapter= InfoAdapterByRecyclerView(list)
        infoRecyclerView.adapter=adapter

    }
    fun initInfo(student: Student):ArrayList<Info>{
        var list=ArrayList<Info>()
        list.add(Info("姓名",student.stuName))
        list.add(Info("学号",student.stuNo))
        list.add(Info("班级",student.classes))
        list.add(Info("性别",student.gender))
        list.add(Info("专业",student.department))
        list.add(Info("宿舍",student.dormNo))
        return list
    }

    private fun loadImage(sex:Int){
        var url:String
        if(sex==1){
            url="girl.jpg"
        }else{
            url="boy.jpeg"
        }
        ServerCreator.create(StudentService::class.java)
            .downloadPic(url)
            .map(object: Func1<ResponseBody, Bitmap> {
                override fun call(t: ResponseBody?):
                        Bitmap {
                    return BitmapFactory.decodeStream(t?.byteStream())
                }
            }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object: Observer<Bitmap> {
                override fun onCompleted() {
//停止pregressBar
                    Log.d("finished","finished.................")
                }
                override fun onError(e: Throwable?) {
                    Log.d("error","error................")
                }
                override fun onNext(t: Bitmap?) {
                    stuImage.setImageBitmap(t)
                }
            })
    }

}